<template>
    <div class="params_container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card>
        <!-- 消息提示 -->
        <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
        <!-- 分类选择表单 -->
        <el-form>
          <el-form-item label='选择商品分类'>
            <!-- 下拉级联选择框 -->
            <el-cascader v-model="cateId" :options="options" @change="handleChangeCat" :props='props'></el-cascader>
          </el-form-item>
        </el-form>
        <!-- tab栏设置属性 -->
        <el-tabs type="border-card" v-model='activePath' @tab-click="handleClick">
          <el-tab-pane label='动态参数' name='many'>
            <el-button type='primary' size='mini' :disabled='isShowbtn' @click='addmanyvisiable = true'>添加参数</el-button>
            <el-table :data='manyTabledata' stripe>
              <!-- 展开列 -->
              <el-table-column type='expand'>
                <template slot-scope='scope'>
                  <el-tag :key="i" v-for="(tag,i) in scope.row.attr_vals" closable :disable-transitions="false" @close="handleClose(i, scope.row)">
                    {{tag}}
                  </el-tag>
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 序列 -->
              <el-table-column type='index'></el-table-column>
              <el-table-column label='参数名' prop='attr_name'></el-table-column>
              <el-table-column label='操作'>
                <template slot-scope='scope'>
                    <!-- 编辑 -->
                    <el-button type="primary" icon="el-icon-edit" size='mini' @click='editRoleDialog(scope.row)'>编辑</el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" icon="el-icon-delete" size='mini' @click='removeRoleById(scope.row)'>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label='静态属性' name='only'>
            <el-button type='primary' size='mini' :disabled='isShowbtn' @click='editvisiable = true'>添加属性</el-button>
            <el-table :data='manyTabledata'>
              <!-- 展开列 -->
              <el-table-column type='expand'>
                <template slot-scope='scope'>
                  <el-tag :key="i" v-for="(tag,i) in scope.row.attr_vals" closable :disable-transitions="false" @close="handleClose(i, scope.row)">
                    {{tag}}
                  </el-tag>
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 序列 -->
              <el-table-column type='index'></el-table-column>
              <el-table-column label='参数名' prop='attr_name'></el-table-column>
              <el-table-column label='操作'>
                <template slot-scope='scope'>
                  <!-- 编辑 -->
                  <el-button type="primary" icon="el-icon-edit" size='mini' @click='editRoleDialog(scope.row)'>编辑</el-button>
                  <!-- 删除按钮 -->
                  <el-button type="danger" icon="el-icon-delete" size='mini' @click='removeRoleById(scope.row)'>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 添加参数的对话框 -->
      <el-dialog :title="'添加' + titleInfo" :visible.sync="addmanyvisiable">
        <el-form :model="addManyData" :rules='addManyDataRules' ref='addManyRef'>
            <el-form-item :label="titleInfo" label-width="120px" prop='attr_name'>
              <el-input v-model="addManyData.attr_name" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addmanyvisiable = false">取 消</el-button>
            <el-button type="primary" @click="addData">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑参数的对话框 -->
      <el-dialog :title="'修改' + titleInfo" :visible.sync="editvisiable">
        <el-form :model="editData" :rules='editDataRules' ref='editDiaRef'>
            <el-form-item :label="titleInfo" label-width="120px" prop='attr_name'>
              <el-input v-model="editData.attr_name" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="editvisiable = false">取 消</el-button>
            <el-button type="primary" @click="editParam">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // 级联菜单展示对象props
      props: {
        label: 'cat_name',
        children: 'children',
        value: 'cat_id'
      },
      // 选择的商品分类id
      cateId: [],
      // 商品分类列表
      options: [],
      // 动态参数信息
      manyTabledata: [],
      // 添加的动态参数
      addManyData: {
        attr_name: ''
      },
      // 添加动态参数表单的校验规则
      addManyDataRules: {
        attr_name: [
          { required: true, message: '请输入待添加的参数或属性', trigger: 'blur' }
        ]
      },
      // 修改参数表单的校验规则
      editDataRules: {
        attr_name: [
          { required: true, message: '请输入修改后的参数或属性', trigger: 'blur' }
        ]
      },
      // 待修改对象
      editData: {},
      // 添加按钮的禁用状况
      isShowbtn: true,
      // 添加动态参数对话框的显示隐藏
      addmanyvisiable: false,
      // 修改参数对话框的显示隐藏
      editvisiable: false,
      // 当前展示的标签页
      activePath: 'many'
    }
  },
  created () {
    this.getGoodcateList()
  },
  computed: {
    // 动态计算标题内容
    titleInfo () {
      if (this.activePath === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    // 获取商品分类列表
    async getGoodcateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('商品分类列表获取失败')
      this.options = res.data
    },
    // 处理标签页间的切换
    handleClick (tab, event) {
      this.manyTabledata = []
      console.log(this.activePath)
      this.getDataList(this.cateId[2])
    },
    handleChangeCat () {
      // 清掉当前列表中展示的数据
      this.manyTabledata = []
      this.isShowbtn = true
      // 如果三级分类被选中了，则可以将添加按钮打开
      if (this.cateId.length === 3) {
        this.isShowbtn = false
      }
      // 三级分类选中后同时获取已经存在的动态参数列表渲染展示出来
      // 当前分类的id
      const id = this.cateId[2]
      this.getDataList(id)
    },
    // 获取对应的参数列表
    async getDataList (id) {
      const { data: res } = await this.$http.get(`categories/${id}/attributes`, {
        params: {
          sel: this.activePath
        }
      })
      console.log(res.data)
      if (res.meta.status !== 200) return this.$message.error('获取参数列表信息失败')
      // 遍历处理res.data中的attr_vals格式,方便展示
      // res.data.forEach(item => {
      //   item.attr_vals = item.attr_vals.split('s')
      // })
      res.data.forEach(item => {
        // 不同的种类返回的参数值数组里那个字符串的分隔符不同,有空格的有逗号的
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框中输入的值
        item.inputValue = ''
      })
      console.log(res.data[0].attr_vals)
      this.manyTabledata = res.data
    },
    // 添加动态参数
    addData () {
      this.$refs.addManyRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入要添加的动态参数')
        }
        const id = this.cateId[2]
        const { data: res } = await this.$http.post(`categories/${id}/attributes`, {
          attr_name: this.addManyData.attr_name,
          attr_sel: this.activePath
        })
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success('添加参数成功')
        this.manyTabledata.push(res.data)
        console.log(this.manyTabledata)
        this.addmanyvisiable = false
      })
    },
    // 点击关闭删除参数同步数据库保持
    handleClose (i, val) {
      val.attr_vals.splice(i, 1)
      this.changeParm(val)
    },
    // 封装修改参数的函数
    async changeParm (row) {
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activePath,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.success('修改参数失败')
      this.$message.success('修改参数成功')
    },
    // 点击出现添加输入框
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 处理回车或点击失去焦点修改参数
    handleInputConfirm (row) {
      let inputValue = row.inputValue
      if (inputValue) {
        row.attr_vals.push(inputValue)
      }
      row.inputVisible = false
      row.inputValue = ''
      this.changeParm(row)
    },
    // 删除功能
    removeRoleById (row) {
      console.log(row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(row.cat_id)
        const { data: res } = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getDataList(this.cateId[2])
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑参数对话框
    editRoleDialog (row) {
      this.editData = row
      console.log(this.editData)
      // 显示编辑参数对话框
      this.editvisiable = true
    },
    // 编辑修改参数
    editParam () {
      this.changeParm(this.editData)
      this.editvisiable = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-alert,
  .el-form{
    margin-bottom: 20px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .el-tag{
    margin-bottom: 10px;
  }
</style>
